set -e

# Load KAEP root dir.
KAEP_TEST_DIR=$(cd $(dirname $0)/; pwd)
echo $KAEP_TEST_DIR

OPTIONS=""
BUILD_TYPE="Debug"
ENABLE_ASAN="OFF"
CMOCKA_DIR="platform/cmocka"
OPENHITLS_DIR="../platform/openhitls"

echo "准备全新构建环境..."
rm -rf "${KAEP_TEST_DIR}/build"
mkdir -p "${KAEP_TEST_DIR}/build"
cd "${KAEP_TEST_DIR}/build" || exit

build_depend_code()
{
    # 构建 Cmocka
    echo "构建 cmocka"
    if [ ! -d "${KAEP_TEST_DIR}/platform/cmocka/build" ]; then
        mkdir -p ${KAEP_TEST_DIR}/platform/cmocka/build
        cd ${KAEP_TEST_DIR}/platform/cmocka/build
        cmake .. && make
        cd -
    fi
}

# 下载依赖
echo "检查依赖项..."
if [ ! -d "${KAEP_TEST_DIR}/${CMOCKA_DIR}" ]; then
    echo "下载 cmocka..."
    mkdir -p "${KAEP_TEST_DIR}/platform"  # 确保父目录存在
    git clone --recurse-submodules https://gitlab.com/cmocka/cmocka.git "${KAEP_TEST_DIR}/${CMOCKA_DIR}"
fi

build_depend_code

if [ -f ${KAEP_TEST_DIR}/${OPENHITLS_DIR}/build/macro.txt ]; then
    CUSTOM_CFLAGS=$(cat ${KAEP_TEST_DIR}/${OPENHITLS_DIR}/build/macro.txt)
    CUSTOM_CFLAGS="$CUSTOM_CFLAGS -D__FILENAME__=__FILE__"
fi

echo ">> Configuring CMake"
cmake .. \
  -DCMAKE_BUILD_TYPE=Debug \
  -DENABLE_ASAN=OFF \
  -DBUILD_SDV=ON \
  -DCMAKE_INSTALL_PREFIX=${KAEP_TEST_DIR} \
  -DCUSTOM_CFLAGS="${CUSTOM_CFLAGS}" \
  -DWD_DIR=/usr/local/include/warpdrive

# 编译
echo ">> Building project..."
make -j$(nproc)

echo "✓ Build completed."
